import loading from "../assets/loading.gif"
import SearchHeader from "../components/SearchPokemonPage/SearchHeader";
import React, {useEffect, useState} from "react";
import NotFound from "../components/SearchPokemonPage/NotFound";
import PokemonCard from "../components/SearchPokemonPage/PokemonCard";
import loadPokemonsByFilter from "../utils/loadPokemonsByFilter";

const SearchPage = () => {
    const [pokemons, setPokemons] = useState([]);
    const [searchText, setSearchText] = useState('');
    const [isSearching, setSearching] = useState(false);
    const [isFound, setFound] = useState(false)
    const [offset, setOffset] = useState(0);
    const [fetching, setFetching] = useState(true);
    const [currentLimit] = useState(70)

    useEffect(() => {
        document.addEventListener('scroll', scrollHandler)

        return function () {
            document.removeEventListener('scroll', scrollHandler)
        }
    });

    const scrollHandler = (e) => {
        if (e.target.documentElement.scrollHeight - (e.target.documentElement.scrollTop + window.innerHeight) < 200 && pokemons.length === offset && !fetching) {
            setFetching(true)
        }
    }

    useEffect(() => {
            if (fetching) {
                if (isSearching) {
                    loadPokemonsByFilter(currentLimit, offset, searchText)
                        .then(json => {
                            if (json.results.name.includes(searchText.toLowerCase())) {
                                if (json.results > 0)
                                    setFound(true)
                                setPokemons(prevPokemons => [...prevPokemons, ...json.results])
                                setOffset(prevOffset => prevOffset + currentLimit)
                                setFetching(false)
                            }
                        })
                        .catch(error => console.error('Error fetching initial data:', error));
                } else {
                    loadPokemonsByFilter(currentLimit, offset)
                        .then(json => {
                                setPokemons(prevPokemons => [...prevPokemons, ...json.results])
                                setOffset(prevOffset => prevOffset + currentLimit)
                                setFetching(false)
                            }
                        )
                        .catch(error => console.error('Error fetching initial data:', error));
                }

            }
        }, [fetching]
    )

    useEffect(() => {
        if (pokemons.length <= 70) {
            setFetching(true)
        }
    }, [isSearching])

    const handleChange = event => {
        setSearchText(event.target.value);
    };

    const handleSubmit = () => {
        setFound(false)
        if (searchText) {
            setSearching(true)
            let results = pokemons.filter(pokemon =>
                pokemon.name.includes(searchText.toLowerCase()))
            setPokemons(results)
            setOffset(results.length)
        } else {
            setPokemons([])
            setSearching(false)
            setFetching(true)
            setOffset(0)
        }
    };

    console.log(offset)

    return (
        <div>
            <SearchHeader inputText={searchText} handleChange={handleChange} handleSubmit={handleSubmit}/>
            <div className="search-page-content">
                {!isSearching ? (
                    pokemons.length === 0 ? (
                        <div className='loading'>
                            <img alt='loading' src={loading}/>
                        </div>
                    ) : (
                        <div className="pokemon-list">
                            <div className="pokemon-list-wrapper">
                                {
                                    pokemons.map(pokemon => (
                                        <PokemonCard id={pokemon.id}
                                                     name={pokemon.name}
                                                     types={pokemon.types.map(i => i.type)}
                                                     img={pokemon.sprites.other.home.front_Default}/>
                                    ))
                                }
                            </div>
                        </div>
                    )
                ) : (
                    isFound ? (
                    <div className="pokemon-list">
                        <div className="pokemon-list-wrapper">
                            {
                                pokemons.map(pokemon => (
                                    <PokemonCard id={pokemon.id}
                                                 name={pokemon.name}
                                                 types={pokemon.types.map(i => i.type)}
                                                 img={pokemon.sprites.other.home.front_Default}/>
                                ))
                            }
                        </div>
                    </div>
                    ) : (
                        <NotFound/>
                    )
                )}
            </div>
        </div>
    );
}

export default SearchPage;